package org.company.management.ui;

import org.company.management.controller.EmployeeGroupJpaController;
import org.company.management.controller.EmployeeJpaController;
import org.company.management.controller.FileController;
import org.company.management.controller.StatusLineController;
import org.company.management.controller.UiController;
import org.company.management.entity.Employee;
import org.company.management.entity.EmployeeGroup;
import org.company.management.utilities.CustomValidatedText;
import org.company.management.utilities.LastNameValidator;
import org.company.management.utilities.NameValidator;
import org.company.management.utilities.PhoneValidator;
import org.company.management.utilities.Strings;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.layout.grouplayout.GroupLayout;
import org.eclipse.wb.swt.layout.grouplayout.LayoutStyle;

/**
 * @author Paner
 *
 */
public class AddEmployeeEditor extends EditorPart implements SelectionListener {

	public static final String ID = Strings.addEmployeeEditorId;
	
	private Group _employeesGroup;
	private Button _backButton;
	private Button _addButton;
	private Button _loadphotoButton;
	private Label _imageLabel;
	private CustomValidatedText _nameText;
	private CustomValidatedText _lastnameText;
	private CustomValidatedText _phoneText;
	private Combo _employeesgroupCombo;
	
	/* 
	 * Constructor, sets title image for editor
	 */
	public AddEmployeeEditor() {
		setTitleImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.addUserPicture16x16));
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);

	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void createPartControl(Composite parent) {
		createControls(parent);
		createLayout(parent);
		fillEditor();
		
	}
	
	/*
	 * Creates widgets
	 */
	private void createControls(Composite parent)
	{
		_employeesGroup = new Group(parent, SWT.NONE);
		_employeesGroup.setText(Strings.newEmployee);
		
		_backButton = new Button(parent, SWT.NONE);
		_backButton.setToolTipText(Strings.backTooltip);
		_backButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.backButtonPicture32x32));
		_backButton.addSelectionListener(this);

		_addButton = new Button(parent, SWT.NONE);
		_addButton.setToolTipText(Strings.confirmTooltip);
		_addButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.confirmButtonPicture32x32));
		_addButton.addSelectionListener(this);
		
		_loadphotoButton = new Button(_employeesGroup, SWT.NONE);
		_loadphotoButton.setToolTipText(Strings.addPhotoTooltip);
		_loadphotoButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.openPhotoPicture32x32));
		_loadphotoButton.addSelectionListener(this);
		_loadphotoButton.setBounds(286, 248, 52, 25);
		
		_nameText = new CustomValidatedText(_employeesGroup, new NameValidator());
		_nameText.setBounds(114, 63, 239, 21);
		
		_lastnameText = new CustomValidatedText(_employeesGroup, new LastNameValidator());
		_lastnameText.setBounds(114, 116, 239, 21);
		
		_phoneText = new CustomValidatedText(_employeesGroup, new PhoneValidator());
		_phoneText.setBounds(114, 171, 239, 21);
		
		_imageLabel = new Label(_employeesGroup, SWT.NONE);
		_imageLabel.setBounds(114, 207, 166, 100);
		
		Label nameLabel = new Label(_employeesGroup, SWT.NONE);
		nameLabel.setBounds(29, 66, 55, 15);
		nameLabel.setText(Strings.name);
		
		Label lastNameLabel = new Label(_employeesGroup, SWT.NONE);
		lastNameLabel.setText(Strings.lastName);
		lastNameLabel.setBounds(29, 119, 71, 15);
		
		Label phoneLabel = new Label(_employeesGroup, SWT.NONE);
		phoneLabel.setText(Strings.phone);
		phoneLabel.setBounds(29, 174, 71, 15);
		
		Label groupLabel = new Label(_employeesGroup, SWT.NONE);
		groupLabel.setText(Strings.group);
		groupLabel.setBounds(29, 316, 55, 15);
		
		Label photoLabel = new Label(_employeesGroup, SWT.NONE);
		photoLabel.setText(Strings.photo);
		photoLabel.setBounds(29, 253, 79, 15);
		
		_employeesgroupCombo = new Combo(_employeesGroup, SWT.READ_ONLY);
		_employeesgroupCombo.setBounds(114, 313, 239, 23);

	}
	
	/*
	 * Creates layout
	 */
	private void createLayout(Composite parent) 
	{
		GroupLayout gl_parent = new GroupLayout(parent);
		gl_parent.setHorizontalGroup(
			gl_parent.createParallelGroup(GroupLayout.TRAILING)
				.add(gl_parent.createSequentialGroup()
					.add(gl_parent.createParallelGroup(GroupLayout.LEADING)
						.add(gl_parent.createSequentialGroup()
							.addContainerGap()
							.add(_backButton))
						.add(gl_parent.createSequentialGroup()
							.add(93)
							.add(_employeesGroup, GroupLayout.PREFERRED_SIZE, 419, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.RELATED, 11, Short.MAX_VALUE)
							.add(_addButton)))
					.addContainerGap())
		);
		gl_parent.setVerticalGroup(
			gl_parent.createParallelGroup(GroupLayout.LEADING)
				.add(gl_parent.createSequentialGroup()
					.add(gl_parent.createParallelGroup(GroupLayout.LEADING)
						.add(gl_parent.createSequentialGroup()
							.addContainerGap()
							.add(_backButton)
							.addPreferredGap(LayoutStyle.RELATED, 398, Short.MAX_VALUE)
							.add(_addButton))
						.add(gl_parent.createSequentialGroup()
							.add(100)
							.add(_employeesGroup, GroupLayout.PREFERRED_SIZE, 341, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		parent.setLayout(gl_parent);
		
	}
	
	/*
	 * Fills the components of the editor
	 */
	private void fillEditor()
	{
		//Fills combo with values
		try
		{
			EmployeeGroupJpaController employeeGroupDao = new EmployeeGroupJpaController();
			_employeesgroupCombo.add("");

			for(EmployeeGroup employeeGroup : employeeGroupDao.findEmployeeGroupEntities())
			{
				_employeesgroupCombo.add(employeeGroup.getName());
				_employeesgroupCombo.setData(employeeGroup);
				
			}
		}
		catch(Exception ex)
		{
			//throw;
		}
		
	}

	/*
	 * Checks that required fields are filled
	 */
	private boolean validateUserInput()
	{
		boolean proceed = false;
		if(_nameText.isValid() && _lastnameText.isValid() && _phoneText.isValid())
		{
			//CustomMessageBox.showWarningMessageBox(Strings.invalidInputHeader, Strings.invalidInputMessage);
			proceed = true;
		}
		
		return proceed;
	}
	
	@Override
	public void widgetSelected(SelectionEvent e) {
		Object selectedWidget = e.getSource();
		if(selectedWidget == _addButton)
		{
			if(validateUserInput())
			{
				try
				{
					//Create and fill a new employee for user given values
					Employee employee = new Employee();
					employee.setName(_nameText.getText());
					employee.setLastname(_lastnameText.getText());
					employee.setPhone(_phoneText.getText());

					String imagePath = null;
					imagePath = (String) _imageLabel.getData();
					
					employee.setPicture(imagePath);
					
					//Set employee group if exists
					if(_employeesgroupCombo.getText() != null && _employeesgroupCombo.getText().length() != 0)
					{
						employee.setGroupid((EmployeeGroup)_employeesgroupCombo.getData());
					}
					
					EmployeeJpaController employeeDao = new EmployeeJpaController();
					employeeDao.create(employee);
					
					StatusLineController.setStatusLine(getEditorSite(), Strings.validInputMessage);

				}
				catch (Exception ex)
				{
					ex.printStackTrace();
				}
				
			}
			else
			{
				StatusLineController.setStatusLine(getEditorSite(), Strings.invalidInputMessage);
			}
		}
		else if (selectedWidget == _backButton)
		{
			UiController.showEditor(Strings.gallery, EmployeeGalleryEditor.ID);
		}
		else if (selectedWidget == _loadphotoButton)
		{
			try
			{
				FileController.openFile();
				String selectedFile = FileController.copyFile();
				Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				Image selectedImage = new Image(shell.getDisplay(), selectedFile);
				_imageLabel.setData(selectedFile);
				_imageLabel.setImage(selectedImage);
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
